<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    :maskClosable="false"
    cancelText="关闭"
    :destroyOnClose="true"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row>
          <a-col :span="12">
            <a-form-item label="客户名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                :disabled="disableSubmit"
                v-decorator="['customerName', validatorRules.customerName]"
                placeholder="请输入客户名称"
              ></a-input>
            </a-form-item>
          </a-col>
          <!--
          <a-col :span="12">
            <a-form-item label="跟进状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                style="width: 80%"
                :disabled="disableSubmit"
                v-decorator="['followUp']"
                placeholder="请输入跟进状态"
              ></a-input>
              %
            </a-form-item>
          </a-col>
          -->
          <a-col :span="12">
            <a-form-item label="客户来源" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag
                :disabled="disableSubmit"
                type="list"
                v-decorator="['source']"
                :trigger-change="true"
                dictCode="DataDictionary,description,dictionaryId, dictionaryTypeId =CRM_SOURCE_TYPE"
                placeholder="请选择客户来源"
              />
            </a-form-item>
          </a-col>
          <!-- <a-col :span="12">
            <a-form-item label="客户行业" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag
                :disabled="disableSubmit"
                type="list"
                v-decorator="['industry', validatorRules.industry]"
                :trigger-change="true"
                dictCode="DataDictionary,description,dictionaryId, dictionaryTypeId =CRM_TRADE_TYPE"
                placeholder="请选择客户行业"
              />
            </a-form-item> -->
          <!-- </a-col> -->
           <a-col :span="12">
            <a-form-item label="关联客户" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-search-select-tag
            :disabled="disableSubmit"
            type="list"
            v-decorator="['relatedCustomer']"
            :trigger-change="true"
            :dict="'CrmCustomer,customerName,id, infoStatusId =3 & id!='+model.batchId"
            placeholder="请选择关联客户"
          />
             
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="客户级别" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag
                :disabled="disableSubmit"
                type="list"
                v-decorator="['level', validatorRules.level]"
                :trigger-change="true"
                dictCode="DataDictionary,description,dictionaryId, dictionaryTypeId =LEVEL_TYPE"
                placeholder="请选择客户级别"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="产品品类" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag
                :disabled="disableSubmit"
                type="list"
                v-decorator="['productCategory', validatorRules.productCategory]"
                :trigger-change="true"
                dictCode="DataDictionary,description,dictionaryId, dictionaryTypeId =PRODUCT_CATEGORY"
                placeholder="请选择客户产品品类"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <!--:dict="'CrmContacts,name,id' + (isAdd?(',ownerUserId='+ownerUserId):(groupId === '4210'? (',ownerUserId='+ownerUserId):''))"-->
            <a-form-item label="首要联系人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-search-select-tag
                ref="contacts"
                :disabled="disableSubmit"
                type="list"
                v-decorator="['contactsId']"
                :trigger-change="true"
                :dictOptions="contactsInfoList"
                :isdropdownRender="true"
                @change="contactsChange"
                @addDropItem="addContacts"
                placeholder="请选择首要联系人"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="手机" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                :disabled="disableSubmit"
                v-decorator="['mobile', validatorRules.mobile]"
                placeholder="请输入手机"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="电话" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                :disabled="disableSubmit"
                v-decorator="['telephone', validatorRules.telephone]"
                placeholder="请输入电话"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="微信" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                :disabled="disableSubmit"
                v-decorator="['wxId']"
                placeholder="请输入微信"
              ></a-input>
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item label="邮箱" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                :disabled="disableSubmit"
                v-decorator="['email', validatorRules.email]"
                placeholder="请输入邮箱"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="生日" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date
                placeholder="请输入生日"
                :show-time="false"
                v-decorator="['birthDate']"
                :trigger-change="true"
                date-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="是否有子女" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag
                :disabled="disableSubmit"
                type="list"
                v-decorator="['hasChild']"
                :trigger-change="true"
                dictCode="DataDictionary,description,dictionaryId, dictionaryTypeId =BOOL_DEFINE"
                placeholder="请选择"
              />
            </a-form-item>
          </a-col>

          <!--
          <a-col :span="12">
            <a-form-item label="下次联系时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date
                placeholder="请输入下次联系时间"
                :show-time="true"
                v-decorator="['nextTime']"
                :trigger-change="true"
                date-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          -->

          <a-col :span="12">
            <a-form-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-textarea :disabled="disableSubmit" v-decorator="['remark']" rows="4" placeholder="请输入备注" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>

      <crm-contacts-modal ref="contract" :customerId="id" @ok="reloadContacts"></crm-contacts-modal>
    </a-spin>
  </j-modal>
</template>

<script>
import CrmContactsModal from '../../contacts/modules/CrmContactsModal.vue'
import { httpAction,getAction  } from '@/api/manage'
import pick from 'lodash.pick'
import { validateDuplicateValue } from '@/utils/util'
import JDictSelectTag from '@/components/dict/JDictSelectTag'
import JSearchSelectTag from '@/components/dict/JSearchSelectTag'

import JDate from '@/components/jeecg/JDate'

import { mapGetters } from 'vuex'

export default {
  name: 'CrmCustomerModal',
  components: {
    JDictSelectTag,
    JDate,
    CrmContactsModal,
    JSearchSelectTag
  },
  data() {
    return {
      ownerUserId: this.userInfo().userLoginId,
      groupId: this.userInfo().groupId,
      disableSubmit: false,
      form: this.$form.createForm(this),
      isAdd: null, 
      title: '操作',
      width: 1000,
      visible: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      validatorRules: {
        customerName: { rules: [{ required: true, message: '请填写客户名称!' }] },
        industry: { rules: [{ required: true, message: '请选择客户行业!' }] },
        level: { rules: [{ required: true, message: '请选择客户基本!' }] },

        productCategory: { rules: [{ required: true, message: '请选择产品品类!' }] },
        mobile: {
          rules: [
            { required: false, message: '请输入手机号!' },
            { pattern: /^1[0-9]{10}$/, message: '请输入正确的手机号!' },
            // { validator: this.validateMode },
          ],
        },
        telephone: {
          rules: [
            { required: false, message: '请输入电话号码!' },
            { pattern: /^([0-9]{3,4}-)?[0-9]{7,8}$/, message: '请输入正确的电话号码!' },
          ],
        },
        wxId: {
          rules: [{ required: false, message: '请输入微信!' }],
        },
        money: {
          rules: [
            {
              pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
              message: '请输入正确的金额!',
            },
          ],
        },
        number: {
          rules: [
            {
              pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
              message: '请输入正确的数字!',
            },
          ],
        },
        email: {
          rules: [
            { required: false, message: '请输入邮箱!' },
            { pattern: /^([a-zA-Z0-9._-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/, message: '请输入正确邮箱!' },
          ],
        },
      },
      id: '',
      url: {
        add: '/online/api/createCrmCustomer',
        edit: '/online/api/updateCrmCustomer',
        get: '/online/api/getCrmCustomer',
        getContacts: 'online/api/getCrmContacts',
      },
      contactsInfoList:[],
    }
  },
  created() {},
  methods: {
    ...mapGetters(['userInfo']),
    validateMode(rule, value, callback) {
      // alert(value);
      if (value == undefined || value == '') {
        if (this.form.getFieldsValue().telephone == undefined) {
          callback('请填写手机号或者电话号码')
          //this.$message.warning("请填写手机号或者电话号码");
        } else {
          callback()
        }
      } else {
        callback()
      }
    },

    add() {
      this.isAdd = true
      this.edit({})
    },
    async edit(record) {
       const res1 = await getAction('/online/api/listByUserIdCrmContacts', {ownerUserId:this.userInfo().userLoginId,contactsId:record.contactsId})
        if (res1.success) {
          console.log(res1.result);
          this.contactsInfoList = res1.result;
        }
      console.log(this.contactsInfoList);

      this.form.resetFields()
      this.visible = true
      this.model = {}
      this.id = ''
      // this.model.level =
      // alert(this.model.level);

      if (this.form.getFieldsValue().level == undefined) {
        this.$nextTick(() => {
          this.form.setFieldsValue({ level: 'LEVEL_NonKA' })
        })
      }

      if (record.id) {
        this.id = record.id
        httpAction(this.url.get, { id: record.id }, 'post').then((res) => {
          if (res.success) {
            this.model = Object.assign({}, res.result)
            this.$nextTick(() => {
              this.form.setFieldsValue(
                pick(
                  this.model,
                  'updateTime',
                  'customerName',
                  'batchId',
                  'followUp',
                  'statusId',
                  'isLock',
                  'lastTime',
                  'nextTime',
                  'poolTime',
                  'dealStatus',
                  'isReceive',
                  'dealTime',
                  'lastContent',
                  'contactsId',
                  'receiveTime',
                  'mobile',
                  'preOwnerUserId',
                  'telephone',
                  'wxId',
                  'website',
                  'email',
                  'remark',
                  'createUserId',
                  'ownerUserId',
                  'roUserId',
                  'rwUserId',
                  'address',
                  'location',
                  'detailAddress',
                  'lng',
                  'lat',
                  'createTime',
                  'updateTime',
                  'batchId',
                  'statusId',
                  'lastTime',
                  'poolTime',
                  'isReceive',
                  'lastContent',
                  'receiveTime',
                  'preOwnerUserId',
                  'source',
                  'industry',
                  'level',
                  'birthDate',
                  'hasChild',
                  'productCategory',
                  'relatedCustomer'
                )
              )
            })
          }
        })
      }
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          let formData = Object.assign(this.model, values)
          if (!formData.mobile && !formData.telephone && !formData.wxId) {
            that.confirmLoading = false
            that.$message.warning('请填写手机、电话、微信其中之一!')
            return
          }
          console.log('表单提交数据', formData)
          httpAction(httpurl, formData, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
                if (that.model.id) {
                  that.$emit('loadDetailInfo', that.model)
                }
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
              that.close()
            })
        }
      })
    },
    handleCancel() {
      this.close()
    },
    popupCallback(row) {
      this.form.setFieldsValue(
        pick(
          row,
          'updateTime',
          'customerName',
          'batchId',
          'followUp',
          'statusId',
          'isLock',
          'lastTime',
          'nextTime',
          'poolTime',
          'dealStatus',
          'isReceive',
          'dealTime',
          'lastContent',
          'contactsId',
          'receiveTime',
          'mobile',
          'preOwnerUserId',
          'telephone',
          'wxId',
          'website',
          'email',
          'remark',
          'createUserId',
          'ownerUserId',
          'roUserId',
          'rwUserId',
          'address',
          'location',
          'detailAddress',
          'lng',
          'lat',
          'createTime',
          'updateTime',
          'batchId',
          'statusId',
          'lastTime',
          'poolTime',
          'isReceive',
          'lastContent',
          'receiveTime',
          'preOwnerUserId',
          'source',
          'industry',
          'level',
          'birthDate',
          'hasChild',
          'productCategory',
          'relatedCustomer'
        )
      )
    },
    addContacts() {
      this.$refs['contract'].add()
    },
    reloadContacts() {
      this.$refs.contacts.initDictData()
    },
    contactsChange(e) {
      getAction(this.url.getContacts, { id: e })
        .then((res) => {
            let info = res.result
            this.$nextTick(() => {
              this.form.setFieldsValue(
                pick(
                  info,
                  'mobile',
                  'telephone',
                  'email'
                )
              )
            })
        })
        .catch(() => {
          
        })
    },
  },
}
</script>

<style lang="less" scoped>
/deep/ .ant-modal-mask {
  z-index: 98;
  background-color: rgb(245, 246, 249);
}
/deep/ .ant-modal-wrap {
  z-index: 99;
}
/deep/ .ant-modal-title {
  color: #333;
  font-weight: 700;
  font-size: 17px;
}
</style>
